package cn.fl.collection.controller;

import cmm.comm.facade.upload.api.IUploadApiService;
import cmm.comm.facade.upload.condition.SysUlFilesRecQueryCondition;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.collection.constant.CollectionConstant;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.constant.PrjBscInfoConstant;
import cn.fl.project.constant.PrjPrdPaySchMConstant;
import cn.fl.project.service.IPrjPrdPaySchMService;
import cn.fl.project.vo.PrjPrdPaySchMVO;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysUlFilesRecService;
import cn.fl.system.service.ISysUsrService;
import cn.fl.system.transform.SysUlFilesRecVOTransform;
import cn.fl.system.vo.SysUlFilesRecVO;
import cn.fl.system.vo.SysUsrVO;
import cn.fl.upload.constant.UploadConstant;
import com.alibaba.fastjson.JSON;
import fl.ass.facade.constant.AssFileConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
* @Description:    委外催收文件管理Controller
* @Author:         liurong
* @CreateDate:     2020/4/22 15:12
* @Version:        1.0
*/
@Controller
@RequestMapping("/clt/auth/file")
public class RskCltAuthFileController {

    @Autowired
    private ISysUlFilesRecService sysUlFilesRecService;

    /**
     *ISysUsrService 服务层BEAN
     */
    @Autowired
    private ISysUsrService sysUsrService;

    @Autowired
    private IUploadApiService uploadApiService;

    @Autowired
    private IPrjPrdPaySchMService prjPrdPaySchMService;

    /**
     * 委外催收-->资料维护
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/toCltFileListPage.do", method = { RequestMethod.GET})
    public ModelAndView toCltFileListPage(HttpServletRequest request, HttpServletResponse response) {
        String pkId = request.getParameter("pkId");
        String edit = request.getParameter("edit");
        String paySchId = request.getParameter("paySchId");
        if (StringUtils.isEmpty(pkId) && StringUtils.isNotEmpty(paySchId)) {
            PrjPrdPaySchMVO prjPrdPaySchMVO = prjPrdPaySchMService.selectById(Long.parseLong(paySchId));
            if (prjPrdPaySchMVO != null) {
                pkId = prjPrdPaySchMVO.getPrjId().toString();
            }
        }
        ModelAndView view = new ModelAndView("collection/rskcltauth/cltAuthFilePage");
        view.addObject("pkId", pkId);
        view.addObject("edit", edit);
        return view;
    }

    /**
     * 初始化文件列表
     */
    @RequestMapping(value = "/initFilesList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initFilesList(HttpServletRequest request) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        String pkId = request.getParameter("pkId");
        String tabNm = request.getParameter("tabNm");
        try {
            Pager page = new Pager();
            if (StringUtils.isNotEmpty(currentPage)) {
                page.setCurrentPage(Integer.parseInt(currentPage));
            }
            if (StringUtils.isNotEmpty(pageSize)) {
                page.setEveryPage(Integer.parseInt(pageSize));
            }
            SysUlFilesRecQueryCondition qc = new SysUlFilesRecQueryCondition();
            if (StringUtils.isEmpty(pkId) || StringUtils.isEmpty(tabNm)) {
                return page;
            }
            String sysCd = CurrentThreadContext.getCurrentSysCd();
            qc.setPkId(pkId);
            // 判断标识确定文件配置编码
            qc.setCfgCd(CollectionConstant.RSK_CLT_AUTH_FILE_CFG);
            qc.setTabNm(tabNm);
            qc.setSysCd(sysCd);//系统代码-必须条件
            page.setCondition(qc);
            List<SysUlFilesRecVO> list = this.sysUlFilesRecService.searchList(qc);
            // 遍历list查询文件上传者-真实姓名
            SysUsrVO usrVo = null;
            if (CollectionUtils.isNotEmpty(list) && list.size() > 0) {
                for (SysUlFilesRecVO vo : list) {
                    usrVo = this.sysUsrService.selectById(vo.getCrtUsrId(), sysCd);
                    vo.setCrtUsrRlNm(usrVo.getRefRlNm());
                }
            }
            page.setResultList(list);
            page.setTotalCount(list.size());
            ListPageVO<SysUlFilesRecVO> listPage = new ListPageVO<SysUlFilesRecVO>(list, list.size());
            return listPage;
        } catch (BaseException e) {
            BaseLogUtils.newLogger("查询委案催收文件列表失败").setKeys("pkId:" + pkId).setThrowable(e).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        } catch (Exception e) {
            BaseLogUtils.newLogger("查询委案催收文件列表失败").setKeys("pkId:" + pkId).setThrowable(e).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        }
    }

    /**
     * 保存委外分案附件信息
     */
    @RequestMapping(value = "/uploadAttchment.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object uploadAttchment(HttpServletRequest request) throws BaseException {
        String attchmnt = request.getParameter("docArray");
        String id = request.getParameter("pkId");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_FILE_UPLOAD_SUCC);
        if (StringUtils.isNotEmpty(attchmnt) && StringUtils.isNotEmpty(id)) {
            // 上传解析
            try {
                // 文件说明
                String fileRem = "委案分案文件上传";
                // 数据表名
                String tabNm = CollectionConstant.TAB_NM;
                // 文件配置
                String cfgCd = CollectionConstant.RSK_CLT_AUTH_FILE_CFG;
                // 组织架构
                String cfgOrgCd = AssFileConstant.ASS_TRAIL_CAR_CFGORG;
                Boolean attchmntPass = this.sysUlFilesRecService.addAttchmnt(id, attchmnt, cfgCd, "10", tabNm, fileRem, null, null, false, cfgOrgCd);
                if (null == attchmntPass || attchmntPass == false) {
                    result.setSuccess(BaseConstant.IS_YESNO_NO);
                    result.setInfo("委案分案附件信息上传失败!");
                    BaseLogUtils.newLogger("委案分案附件信息上传失败").setKeys("pkId:" + id).info();
                }
                result.setData(id);
            } catch (BaseException ex) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(ex.getMessage());
                BaseLogUtils.newLogger("委案催收附件信息上传失败").setKeys("pkId:" + id, "docArray:" + attchmnt).setThrowable(ex).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            } catch (Exception ex) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
                BaseLogUtils.newLogger("委案催收附件信息上传失败").setKeys("pkId:" + id, "docArray:" + attchmnt).setThrowable(ex).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            }
        }
        return result;
    }

    /**
     * 上传委外分案资料
     * @param request
     * @return
     * @throws BaseException
     */
    @RequestMapping(value = "/uploadCltAuthFile.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object uploadCltAuthFile(HttpServletRequest request) throws BaseException {
        String fileParams = request.getParameter("fileParams");
        String pkId = request.getParameter("pkId");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_FILE_UPLOAD_SUCC);
        try {
            if (StringUtils.isEmpty(pkId)) {
                throw new BaseException("附件资料关联ID不能为空！");
            }
            if (StringUtils.isEmpty(fileParams)) {
                throw new BaseException("请上传附件！");
            }
            List<SysUlFilesRecVO> fileList = JSON.parseArray(fileParams, SysUlFilesRecVO.class);
            if (CollectionUtils.isEmpty(fileList)) {
                throw new BaseException(SysLogConstant.LOG_CMM_SYS_ERROR, "请上传附件！");
            }
            for (SysUlFilesRecVO sysUlFilesRecVO : fileList) {
                sysUlFilesRecVO.setSysCd(CurrentThreadContext.getCurrentSysCd());
                sysUlFilesRecVO.setOrgCd(PrjBscInfoConstant.CODE_PRJ_FILE_DEF_ORG);
                sysUlFilesRecVO.setAbsLocPath(PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_ROOT_PATH) + sysUlFilesRecVO.getFilePath());
                sysUlFilesRecVO.setTabNm(CollectionConstant.TAB_NM);
                sysUlFilesRecVO.setIsDel(BaseConstant.IS_YESNO_NO);
                sysUlFilesRecVO.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
                sysUlFilesRecVO.setSysCd(CurrentThreadContext.getCurrentSysCd());
                sysUlFilesRecVO.setCfgCd(CollectionConstant.RSK_CLT_AUTH_FILE_CFG);
                sysUlFilesRecVO.setCfgDtlCd(PrjPrdPaySchMConstant.PRJ_PRD_Pay_SCH_M_FILE_DETAIL_CODE);
                sysUlFilesRecVO.setAbsLocPath(PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_ROOT_PATH) + sysUlFilesRecVO.getFilePath());
                sysUlFilesRecVO.setPkId(pkId);
                sysUlFilesRecVO.setCrtTm(new Date());
                sysUlFilesRecVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
                sysUlFilesRecVO.setMdfTm(new Date());
                sysUlFilesRecVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
            }
            Boolean bol = uploadApiService.addSysUlFilesRecList(SysUlFilesRecVOTransform.toDTOList(fileList));
            if (bol == null || !bol) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_FILE_UPLOAD_FAIL);
            }
        } catch (BaseException e) {
            BaseLogUtils.newLogger("委外分案-->上传资料业务异常！" + CurrentThreadContext.getCurrentUserName()).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_FILE_UPLOAD_FAIL + "：" + e.getMessage());
        } catch (Exception e) {
            BaseLogUtils.newLogger("委外分案-->上传资料系统异常！" + CurrentThreadContext.getCurrentUserName()).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_FILE_UPLOAD_FAIL);
        }
        return result;
    }

}
